<template>
  <a-spin :spinning="confirmLoading">
    <div v-if="title.indexOf('关联产品') > - 1">
      <a-input-search placeholder="请输入关键字按回车进行搜索" style="margin-bottom: 10px;" v-model="model.searchContent" @search="handleSearch" />
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        class="j-table-force-nowrap"
      >
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="width: 80px;height: 80px;object-fit: cover;cursor: pointer;border-radius: 4px;" @click="handleImg(text)"/>
        </template>
        <template slot="productInfoSlot" slot-scope="text, record">
          <div style="text-align: left; white-space: pre-wrap;">
            <p style="font-size: 14px; font-weight: 700;">{{ record.skuCode }}</p>
            <p>英文名称：{{ record.title }}</p>
            <p>中文名称：{{ record.name }}</p>
            <p>产品类目：{{ record.categoryFullName }}</p>
          </div>
        </template>
      </a-table>
    </div>
    <j-form-container :disabled="formDisabled" v-else>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row v-if="title === '元素标签'">
          <a-col :span="24">
            <a-form-model-item label="元素标签" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="elementTagId">
              <a-select v-model="model.elementTagId" style="width: 100%" placeholder="请选择元素标签">
                <a-select-option v-for="(tag,index) in elementTagOptions" :key="tag.id" :value="tag.id">
                  <a-tag class="tag" :color="tag.color">
                    <j-ellipsis :value="tag.name" :length="10" />
                  </a-tag>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-else>
          <a-col :span="24">
            <a-form-model-item label="元素名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model.trim="model.name" placeholder="请输入元素名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="元素标签" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="elementTagId">
              <a-select v-model="model.elementTagId" style="width: 100%" placeholder="请选择元素标签">
                <a-select-option v-for="(tag,index) in elementTagOptions" :key="tag.id" :value="tag.id">
                  <a-tag class="tag" :color="tag.color">
                    <j-ellipsis :value="tag.name" :length="10" />
                  </a-tag>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="元素图" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="elementImageList">
              <j-upload-oss v-model="model.elementImageList" fileType="image" bizPath="product" :number="20" @handleRemove="handleRemove" @handleAdd="handleAdd"></j-upload-oss>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'ProductLibraryElementForm',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        disableMixinCreated: true,
        elementTagOptions: [],
        deleteImg: [],
        oriModel: {},
        addImg: [],
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          name: [
            { required: true, message: '请输入标签名称!'},
          ],
          elementTagId: [
            { required: true, message: '请输入标签类型!'},
          ],
          elementImageList: [
          { required: true, message: '请上传元素图!'},
          ]
        },
        url: {
          add: "/hzkj-product/product/productLibrary/element/add",
          edit: "/hzkj-product/product/productLibrary/element/edit",
          queryById: "/hzkj-product/product/productLibrary/element/queryById",
          elementTagList: "/hzkj-product/product/productLibrary/elementTag/list",
          list: "/hzkj-product/product/productLibrary/element/selectSkuListByElementId"
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'产品图片',
            align:"center",
            dataIndex: 'productImage',
            scopedSlots: { customRender: 'imgSlot' }
          },
          {
            title:'产品信息',
            align:"center",
            dataIndex: 'productInfo',
            scopedSlots: { customRender: 'productInfoSlot' }
          }
        ],
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.oriModel = Object.assign({}, record);
        if(this.model.id && this.model.elementImageList && this.model.elementImageList.length){
          this.model.elementImageList =  this.model.elementImageList.map(item => item.imageUrl);
          this.model.elementImageList = this.model.elementImageList.join(',');
        }
        if(this.title.indexOf('关联产品') > - 1){
          this.queryParam = {
            id: this.model.id,
            searchContent: this.model.searchContent
          }
          this.loadData();
        }else{
          this.getElementTagList();
        }
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            let httpurl = '';
            let method = '';
            let params = Object.assign({}, this.model);
            let elementImageList = params.elementImageList.split(',') || [];
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
              params.elementImageList = elementImageList.map(item => {
                return {
                  imageUrl: item
                }
              })
            }else{
              httpurl+=this.url.edit;
              method = 'put';
              let elementImageList = this.addImg.map(item => {
                return {
                  imageUrl: item
                }
              })
              let deleteImg = this.deleteImg.map(item => {
                return {
                  ...item,
                  isDeleted: true
                }
              })
              params.elementImageList = [...this.oriModel.elementImageList, ...elementImageList, ...deleteImg];
            }
            that.confirmLoading = true;
            httpAction(httpurl,params,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      handleRemove(index){
        if(this.oriModel.elementImageList && index < this.oriModel.elementImageList.length){
          this.deleteImg.push(this.oriModel.elementImageList[index]);
          this.oriModel.elementImageList.splice(index, 1);
        }
      },
      handleAdd(url){
        this.addImg.push(url);
      },
      getElementTagList(){
        let params = {};
        if(this.title === '元素标签'){
          params = { includeIds: this.model.elementTagId };
        }
        getAction(this.url.elementTagList, params).then((res) => {
          if(res.success){
            this.elementTagOptions = res.result && res.result.records || [];
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleImg(src){
        if(src){
          this.$viewerApi({images: [src]});
        }
      },
      handleSearch(){
        this.queryParam = {
          id: this.model.id,
          searchContent: this.model.searchContent
        }
        this.loadData();
      }
    }
  }
</script>